package com.picshare.controller;

import com.picshare.config.ServerConfig;
import com.picshare.model.FileItem;
import com.picshare.model.ShareLink;
import com.picshare.service.FileService;
import com.picshare.service.ShareService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriUtils;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Controller
public class ShareController {
    
    @Autowired
    private ShareService shareService;
    
    @Autowired
    private FileService fileService;
    
    @PostMapping("/share/create")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> createShare(@RequestParam String fileId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            ShareLink shareLink = shareService.createShareLink(fileId);
            String shareUrl = shareService.getShareUrl(shareLink.getToken());
            
            result.put("success", true);
            result.put("shareUrl", shareUrl);
            result.put("token", shareLink.getToken());
            result.put("expireMinutes", 30);
            result.put("maxDownloads", 10);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "创建分享链接失败: " + e.getMessage());
        }
        
        return ResponseEntity.ok(result);
    }
    
    @PostMapping("/share/batch-create")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> createBatchShare(@RequestParam String fileIds) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 解析文件ID列表
            List<String> fileIdList = Arrays.stream(fileIds.split(","))
                    .map(String::trim)
                    .filter(id -> !id.isEmpty())
                    .collect(Collectors.toList());
            
            if (fileIdList.isEmpty()) {
                result.put("success", false);
                result.put("message", "请选择要分享的文件");
                return ResponseEntity.ok(result);
            }
            
            // 创建批量分享链接
            ShareLink shareLink = shareService.createBatchShareLink(fileIdList);
            String shareUrl = shareService.getShareUrl(shareLink.getToken());
            
            result.put("success", true);
            result.put("shareUrl", shareUrl);
            result.put("token", shareLink.getToken());
            result.put("expireMinutes", 30);
            result.put("maxDownloads", 10);
            result.put("fileCount", fileIdList.size());
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "创建批量分享链接失败: " + e.getMessage());
        }
        
        return ResponseEntity.ok(result);
    }
    
    @GetMapping("/share/qrcode/{token}")
    public ResponseEntity<byte[]> getQRCode(@PathVariable String token) {
        try {
            String shareUrl = shareService.getShareUrl(token);
            byte[] qrCode = shareService.generateQRCode(shareUrl);
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_PNG);
            
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(qrCode);
                    
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }
    
    @GetMapping("/share/{token}")
    public String sharePage(@PathVariable String token, Model model) {
        // 先尝试批量分享
        List<FileItem> basicBatchFiles = shareService.validateBatchShare(token, false);
        if (basicBatchFiles != null && !basicBatchFiles.isEmpty()) {
            // 从FileService获取完整的文件信息
            List<FileItem> completeBatchFiles = new ArrayList<>();
            for (FileItem basicFile : basicBatchFiles) {
                FileItem completeFile = fileService.getFileById(basicFile.getId());
                if (completeFile != null) {
                    completeBatchFiles.add(completeFile);
                }
            }

            if (completeBatchFiles.isEmpty()) {
                model.addAttribute("error", "分享的文件不存在");
                return "share-list";
            }

            model.addAttribute("files", completeBatchFiles);
            model.addAttribute("token", token);
            model.addAttribute("isBatch", true);
            return "share-list";
        }
        
        // 如果不是批量分享，尝试单个文件分享
        FileItem shareFileItem = shareService.validateShare(token, false);
        if (shareFileItem == null) {
            model.addAttribute("error", "分享链接已失效或下载次数已用完");
            return "share-list";
        }

        // 从FileService获取完整的文件信息
        FileItem completeFileItem = fileService.getFileById(shareFileItem.getId());
        if (completeFileItem == null) {
            model.addAttribute("error", "分享的文件不存在");
            return "share-list";
        }

        // 返回单个文件的列表
        List<FileItem> files = new ArrayList<>();
        files.add(completeFileItem);
        model.addAttribute("files", files);
        model.addAttribute("token", token);
        model.addAttribute("isBatch", false);
        return "share-list";
    }
    
    @GetMapping("/share/download/{fileId}")
    public ResponseEntity<byte[]> downloadFile(@PathVariable String fileId, @RequestParam(required = false) String token) {
        // 如果有token，先验证分享链接，下载时增加下载次数
        if (token != null && !token.isEmpty()) {
            FileItem sharedFile = shareService.validateShare(token, true);
            if (sharedFile == null || !sharedFile.getId().equals(fileId)) {
                return ResponseEntity.notFound().build();
            }
        }
        
        FileItem fileItem = fileService.getFileById(fileId);
        if (fileItem == null) {
            return ResponseEntity.notFound().build();
        }
        
        try {
            Path filePath = Paths.get("./albums", fileItem.getFileName());
            if (!Files.exists(filePath)) {
                return ResponseEntity.notFound().build();
            }
            
            byte[] fileBytes = Files.readAllBytes(filePath);
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            String encodedFileName = UriUtils.encode(fileItem.getOriginalName(), StandardCharsets.UTF_8);
            headers.add("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"; filename*=UTF-8''" + encodedFileName);
            headers.setContentLength(fileBytes.length);
            
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(fileBytes);
                    
        } catch (IOException e) {
            return ResponseEntity.internalServerError().build();
        }
    }
    
    @GetMapping("/share/view/{fileId}")
    public ResponseEntity<byte[]> viewFile(@PathVariable String fileId, @RequestParam(required = false) String token) {
        // 如果有token，先验证分享链接，查看不增加下载次数
        if (token != null && !token.isEmpty()) {
            FileItem sharedFile = shareService.validateShare(token, false);
            if (sharedFile == null || !sharedFile.getId().equals(fileId)) {
                return ResponseEntity.notFound().build();
            }
        }
        
        FileItem fileItem = fileService.getFileById(fileId);
        if (fileItem == null) {
            return ResponseEntity.notFound().build();
        }
        
        try {
            Path filePath = Paths.get("./albums", fileItem.getFileName());
            if (!Files.exists(filePath)) {
                return ResponseEntity.notFound().build();
            }
            
            byte[] fileBytes = Files.readAllBytes(filePath);
            
            // 根据文件类型设置Content-Type
            String contentType = getContentType(fileItem.getType());
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType(contentType));
            headers.setContentLength(fileBytes.length);
            
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(fileBytes);
                    
        } catch (IOException e) {
            return ResponseEntity.internalServerError().build();
        }
    }
    
    @GetMapping("/share/batch-download")
    public ResponseEntity<byte[]> batchDownload(@RequestParam String token) {
        // 验证批量分享链接，下载时增加下载次数
        List<FileItem> files = shareService.validateBatchShare(token, true);
        if (files == null || files.isEmpty()) {
            return ResponseEntity.notFound().build();
        }
        
        try {
            // 创建临时字节数组输出流来生成ZIP文件
            java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
            ZipOutputStream zos = new ZipOutputStream(baos);
            
            // 添加所有文件到ZIP压缩包
            for (FileItem file : files) {
                Path filePath = Paths.get("./albums", file.getFileName());
                if (Files.exists(filePath)) {
                    ZipEntry zipEntry = new ZipEntry(file.getOriginalName());
                    zos.putNextEntry(zipEntry);
                    
                    byte[] fileBytes = Files.readAllBytes(filePath);
                    zos.write(fileBytes);
                    
                    zos.closeEntry();
                }
            }
            
            zos.close();
            byte[] zipBytes = baos.toByteArray();
            
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            String zipFileName = "picshare_files_" + System.currentTimeMillis() + ".zip";
            String encodedFileName = UriUtils.encode(zipFileName, StandardCharsets.UTF_8);
            headers.add("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"; filename*=UTF-8''" + encodedFileName);
            headers.setContentLength(zipBytes.length);
            
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(zipBytes);
                    
        } catch (IOException e) {
            return ResponseEntity.internalServerError().build();
        }
    }
    
    private String getContentType(String fileExtension) {
        switch (fileExtension.toLowerCase()) {
            case "jpg":
            case "jpeg":
                return "image/jpeg";
            case "png":
                return "image/png";
            case "gif":
                return "image/gif";
            case "webp":
                return "image/webp";
            case "bmp":
                return "image/bmp";
            case "tiff":
                return "image/tiff";
            case "svg":
                return "image/svg+xml";
            case "pdf":
                return "application/pdf";
            case "txt":
                return "text/plain";
            case "doc":
            case "docx":
                return "application/msword";
            case "xls":
            case "xlsx":
                return "application/vnd.ms-excel";
            case "ppt":
            case "pptx":
                return "application/vnd.ms-powerpoint";
            default:
                return "application/octet-stream";
        }
    }
}